<template>
  <el-card shadow="never"
           :style="{height: gadgetHeight + 'px'}"
           class="aui-card--fill">
    <div class=control-section>
      <div class=content-wrapper
           v-loading="loading">
        <ejs-chart v-if="isHasData"
                   ref="botlinechart"
                   :theme='theme'
                    :style="{height: gadgetHeight-10 + 'px'}"
                    align='center'
                    :width='chartWidth'
                   :title='gadgetSetting.title'
                   :primaryXAxis='gadgetSetting.primaryXAxis'
                   :primaryYAxis='gadgetSetting.primaryYAxis'
                   :tooltip='gadgetSetting.tooltip'
                   :chartArea='gadgetSetting.chartArea'>
          <e-series-collection>
            <e-series :dataSource='dataSource'
                      :type='gadgetSetting.type'
                      xName='createDate'
                      yName='totalNum'
                      :name='gadgetSetting.name'
                      width=2
                      :marker='gadgetSetting.marker'> </e-series>
            <e-series :dataSource='dataSource'
                      xName='createDate'
                      yName='point'
                      dashArray="5,1"
                      :name='gadgetSetting.name'
                      width=2
                      :marker='marker'
                      :type='gadgetSetting.type'
                      >
              <e-trendlines>
                  <e-trendline :type='type' :width='3' :marker='marker'   :name='gadgetSetting.name' fill='#C64A75'>
                  </e-trendline>
              </e-trendlines>
                      </e-series>
          </e-series-collection>
        </ejs-chart>
        <div v-else
             class="gadget-no-data">
          <el-image @click="query()" :src='noDataImageUrl'
                    fit='fill'></el-image>
        </div>
      </div>
    </div>
    <model   :showSetting='queryModelDefaultSetting.showSetting' @queryModelClosed='queryModelClosed'
    :dataInfo='queryModelDefaultSetting.dataInfo' :updateGadget="upgradeGadgetSetting"/>
  </el-card>
</template>

<script>
import mixinGadgetViewModule from '@/mixins/gadget-view-module'

import moment from 'moment'
let selectedTheme = location.hash.split('/')[1]
selectedTheme = selectedTheme || 'Material'
let theme = (selectedTheme.charAt(0).toUpperCase() + selectedTheme.slice(1)).replace(/-dark/i, 'Dark')

export default ({
  mixins: [mixinGadgetViewModule],
  components: { model: () => import('@/components/gadget/query-model/query-model') },
  data: function () {
    return {
      theme: theme,
      dataSource: [
      ],
      gadgetSetting: null,
      loading: false,
      chartWidth: '700px',
      marker: {
        visible: false
      },
      type: 'Linear',
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetType: 'bottriggerreportgadget',
          gadgetSetting: {
            type: 'Line',
            name: '',
            title: 'Bot Trigger Report',
            primaryXAxis: {
              title: 'Dates',
              valueType: 'Category',
              // valueType: 'DateTime',
              // labelFormat: 'Md',
              // intervalType: 'Days',
              // edgeLabelPlacement: 'Shift',
              majorGridLines: {
                width: 0
              }
            },
            primaryYAxis: {
              title: 'Count',
              labelFormat: '{value}',
              rangePadding: 'None',
              minimum: 0,
              maximum: 200,
              interval: 100,
              lineStyle: {
                width: 0
              },
              majorTickLines: {
                width: 0
              },
              minorTickLines: {
                width: 0
              }
            },
            chartArea: {
              border: {
                width: 0
              }
            },
            marker: {
              visible: true,
              height: 10,
              width: 10
            },
            tooltip: {
              enable: true
            }
          }
        }
      }
    }
  },

  created () {
    this.gadgetHeight = (this.gadgetInfo.h * 20) - 20
    if (this.slicer) {
      if (this.slicer.ruleId && this.slicer.userId) {
        // this.query()
      }
    }
    this.$store.state.isWidget = false
    this.subscribeMessage('runReport', this.query)
  },
  methods: {
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query()
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    resized (i, newH, newW, newHPx, newWPx) {
      this.gadgetHeight = (newH * 20) - 20
      this.gadgetWidth = newWPx
      this.chartWidth = (newWPx - 50) + 'px'
    },
    containerResizedEvent (i, newH, newW, newHPx, newWPx) {
      this.chartWidth = (newWPx - 50) + 'px'
    },
    query () {
      this.gadgetSetting = this.queryModelDefaultSetting.dataInfo.gadgetSetting
      this.loading = true
      this.isHasData = false
      var _self = this
      var param = {
        ..._self.slicer,
        createDateFrom: _self.slicer.dateFrom,
        createDateTo: _self.slicer.dateTo,
        dateFrom: moment(_self.slicer.dateFrom).utc().tz(this.$store.state.user.timezoneId).format('YYYY-MM-DD'),
        dateTo: moment(_self.slicer.dateTo).utc().tz(this.$store.state.user.timezoneId).format('YYYY-MM-DD'),
        businessId: this.pageId,
        gadgetId: this.id,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName,
        timezoneOffset: this.$store.state.user.timezoneOffset
      }
      this.$interface.clientDesired.getBotTriggerReportApi(param).then(({ data: res }) => {
        _self.verifyHasData(res)
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        _self.afterQuery(res.data)
        res.data.forEach(item => {
          item.createDate = item.createDate.substr(5)
        })
        _self.dataSource = res.data
        _self.$refs.botlinechart.ej2Instances.refresh()
        this.loading = false
        this.isHasData = true
      }).catch(() => {
        this.loading = false
        this.isHasData = true
      })
    },
    afterQuery (data) {
      var maxtotalNum = this._.maxBy(data, function (o) { return o.totalNum })
      var maxpoint = this._.maxBy(data, function (o) { return o.point })
      var mintotalNum = this._.minBy(data, function (o) { return o.totalNum })
      var minpoint = this._.minBy(data, function (o) { return o.point })
      var max = maxtotalNum.totalNum > maxpoint.point ? maxtotalNum.totalNum : maxpoint.point
      var min = mintotalNum.totalNum < minpoint.point ? mintotalNum.totalNum : minpoint.point
      this.gadgetSetting.primaryYAxis.maximum = Math.ceil(max)
      this.gadgetSetting.primaryYAxis.minimum = Math.floor(min)
      if ((max - min) > 5) {
        this.gadgetSetting.primaryYAxis.interval = this._.ceil(this._.divide([(max - min), 5]))
      }
      this.gadgetSetting.primaryYAxis.interval = Math.ceil(max)
    }
  }

})
</script>
<style scoped>
</style>
